package cn.virens.common.boot.filter.autoconfig;

import cn.virens.common.boot.filter.FilterRegistrationBeanAware;
import cn.virens.common.boot.filter.ajax.SimpleHandlerAjaxSignFilter;
import cn.virens.common.boot.filter.ajax.SimpleHandlerAjaxSignProperties;
import cn.virens.common.util.exception.APIException;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@EnableConfigurationProperties(SimpleHandlerAjaxSignProperties.class)
@ConditionalOnProperty(prefix = "virens.filter.ajax", value = "enabled")
public class SimpleHandlerAjaxSignAutoConfig {

    @Bean(value = "simpleHandlerAjaxSignFilter")
    @ConditionalOnMissingBean(name = "simpleHandlerAjaxSignFilter")
    public FilterRegistrationBean<SimpleHandlerAjaxSignFilter> simpleHandlerAjaxSignFilter(SimpleHandlerAjaxSignProperties properties) throws APIException {
        SimpleHandlerAjaxSignFilter simpleHandlerAjaxSignFilter = new SimpleHandlerAjaxSignFilter(properties);
        properties.pushBlackPatterns(simpleHandlerAjaxSignFilter::addBlackPatterns);
        properties.pushWhitePatterns(simpleHandlerAjaxSignFilter::addWhitePatterns);

        var registrationBean = new FilterRegistrationBeanAware<SimpleHandlerAjaxSignFilter>();
        registrationBean.setOrder(SimpleFilterOrdered.FILTER_AJAX_SIGN);
        registrationBean.setFilter(simpleHandlerAjaxSignFilter);
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }
}
